<!--  -->
<template>

    <FullScreenBorder class="background">

        <starBackground></starBackground>
        <dv-loading v-if="IsLoading == 1">Loading...</dv-loading>

        <div v-if="IsLoading == 0" class="m-data-screen "
            style="padding-left: 20px;padding-right: 20px;padding-bottom: 20px;">
            <bigheader ref="childRef" title="包装机监控中心" @update:menuId="handleMenuIdChange"
                :beforeChange="isMockBeforeChange" :isMock="isMock" />


            <div v-if="parentMenuId == '2'" class="page">
                <indicators :indicators="indicatorsData" />
                <div style="display: flex;gap: 16px;">
                    <!-- 第1行左 -->
                    <div class="flex-col" style="flex: 6.5;">
                        <Station1Card :stationData="wsData.workData.work01" />
                    </div>
                    <!-- 第1行右 -->
                    <div class="flex-col" style="flex: 3.5;">
                        <PaperboardUtilizationRate :data="carboardUsages" />
                    </div>
                </div>
                <div class="content" style="overflow: hidden;padding-top: 16px;">
                    <div class="flex-col" style="flex: 6.5;">
                        <StationsTable :stationsData="wsData.workData.positions" />
                    </div>
                    <div class="flex-col" style="flex: 3.5;">

                        <div class="root">
                            <alarm :orders="abnormalOrders" @retry="RetryInput" @manual="ManualInput" />
                        </div>
                    </div>
                </div>
            </div>
            <div v-if="parentMenuId == '1'" class="page">
                <!-- 使用通用表格组件 -->
                <CommonTable style="height: 100%;" title="待处理订单" :columns="tableColumns" :data="taskOrders"
                    :test-data="testStationsData" :row-class="getRowClass">
                    <!-- 插槽示例：为操作列添加按钮 -->
                    <template #operation="{ row }">
                        <el-button size="small" type="primary" @click="handleRebind(row)">
                            重新绑定
                        </el-button>
                        <!-- <el-button size="small" type="primary" @click="">
                            上传系统
                        </el-button> -->
                        <el-button size="small" type="danger" @click="handleDelete(row)">
                            删除订单
                        </el-button>
                        <el-button size="small" type="primary" @click="handlePrint(row)">
                            打印面单
                        </el-button>
                        <el-button size="small" type="primary" @click="handleUnbind(row)">
                            解除箱号
                        </el-button>
                    </template>

                    <!-- 插槽示例：自定义状态列显示 -->
                    <template #taskStatus="{ row }">
                        <span class="status-tag" :class="getStatusClass(row.status)">
                            {{ getStatusText(row.status) }}
                        </span>
                    </template>
                </CommonTable>
            </div>

        </div>

        <!-- 引入弹框组件 -->
        <RebindDialog ref="rebindDialogRef" :task-number="currentTaskNumber" :old-box-number="currentOldBoxNumber" />



    </FullScreenBorder>
</template>

<script setup name="sd/bigscreendemo01">
import FullScreenBorder from './components/FullScreenBorder.vue'
import starBackground from '@/views/components/starBackground.vue'

import Station1Card from './components/Station1Card.vue'
import StationsTable from './components/StationsTable.vue'
import CommonTable from './components/CommonTable.vue'
import RebindDialog from './components/RebindDialog.vue'
import itemgroup4 from './components/itemgroup4.vue'
import itemgroup5 from './components/itemgroup5.vue'
import itemgroup6 from './components/itemgroup6.vue'
import PaperboardUtilizationRate from './components/PaperboardUtilizationRate.vue'
import alarm from './components/AbnormalOrders.vue'
import bigheader from './components/header.vue'
import indicators from './components/indicators.vue'
import PackagingProcess from './components/PackagingProcess.vue'

import request, { downFile } from '@/utils/request'
const { proxy } = getCurrentInstance()
proxy.signalr.start()
const SR = proxy.signalr.SR





onMounted(() => {
    setTimeout(() => {
        IsLoading.value = 0;
        Online()
    }, 999);
})


const IsLoading = ref(1)




//绑定OEE信息
const wsData = reactive({
    workData: {
        work01: {}
    }
})


const indicatorsData = ref(buildIndicatorsData())

function buildIndicatorsData(data) {

    var finishRate = (data?.finishRate * 100).toFixed(2) + '%'
    return [
        { label: '接收数量', value: data?.receiveCount || '-' },
        { label: '完成数量', value: data?.finishCount || '-' },

        { label: '完成比例', value: data?.finishRate == 0 ? '-' : `${finishRate}` },
        { label: '完成时间', value: data?.onceTime == 0 ? '-' : `${data?.onceTime}s` },
    ]
}



// 父组件中定义变量接收 menuId
const parentMenuId = ref('1');

// 处理子组件传递过来的 menuId
const handleMenuIdChange = (value) => {
    parentMenuId.value = value; // 更新父组件的变量
};



//注册 signalr
function Online() {
    SR.invoke('Demo01Request', 1)
    SR.off('bigScreenDemo01Receive')
    SR.on("bigScreenDemo01Receive", (data) => {
        Object.assign(wsData, data)
        //wsData.value = data

        carboardUsages.value = data.carboardUsages

        //alarms.value = data.alarms
        indicatorsData.value = buildIndicatorsData(data)
        abnormalOrders.value = data.exceptionTasks
        taskOrders.value = data.taskOrders
        isMock.value = data.isMock
        //console.log(data.exceptionTasks,'data.exceptionTasks')
    })
    SR.onreconnected((connectionId) => {
        console.log('大屏断线重新连接成功' + connectionId)
        SR.invoke('Demo01Request', 1)
    })
    console.log('demo01大屏注册通信完成')
}





onMounted(() => {
    window.addEventListener('beforeunload', handleBeforeUnload);
    /* 页面挂载时调用signalr注册大屏上线 */

});

onUnmounted(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload);
});
//
function handleBeforeUnload(event) {
    // 这里可以执行你的清理或保存操作
    SR.invoke('Demo01Request', 0)
    // event.preventDefault(); // 注意：在某些浏览器中，如果你调用了 preventDefault，可能会显示一个对话框询问用户是否真的要离开。
    event.returnValue = ''; // Chrome 需要这个返回值来阻止对话框显示
}




// 各个工站/工位的信息，示例数据
const carboardUsages = ref([
    // { id: 1, title: '项目 1', content: '这是项目1的内容' },

]);

const alarms = ref([
    // { content: '1工位A1 - 温度超阈值', alarmTime: '2023-07-25 10:15', level: 'critical' },
    //         { content: '2工位B3 - 设备超时', alarmTime: '2023-07-25 10:10', level: 'warning' },
    //         { content: '3物料区 - 库存低', alarmTime: '2023-07-25 10:05', level: 'info' },
    //         { content: '4工位C5 - 传送带异常', alarmTime: '2023-07-25 10:00', level: 'warning' },
    // { content: '5质检区 - 合格率低', alarmTime: '2023-07-25 09:55', level: 'critical' },
    // { content: '6电源模块 - 电压波动', alarmTime: '2023-07-25 09:50', level: 'info' },
    // { content: '7工位D2 - 机械臂偏差', alarmTime: '2023-07-25 09:45', level: 'warning' },
    // { content: '8冷却系统 - 流量不足', alarmTime: '2023-07-25 09:40', level: 'critical' },
    // { content: '9仓储区 - 物料过期', alarmTime: '2023-07-25 09:35', level: 'info' },
    // { content: '10工位E7 - 传感器无响应', alarmTime: '2023-07-25 09:30', level: 'warning' },
    // { content: '11包装区 - 封箱不牢', alarmTime: '2023-07-25 09:25', level: 'info' } 
])

// 异常订单样例数据
const abnormalOrders = ref([
    // {
    //   boxNumber: "BX20230801003",
    //   waybillNumber: "YD884567890125",
    //   ngInfo: "地址信息不完整",
    //   occurTime: "2023-08-12 08:40:05"
    // },

]);


// 计算属性：将数据按每页6个进行分组
const carouselPages = computed(() => {

    const pages = [];
    for (let i = 0; i < carboardUsages.value.length; i += 6) {
        pages.push(carboardUsages.value.slice(i, i + 6));
    }
    return pages;
});


const RetryInput = (item) => {

    proxy.$modal.msgSuccess("消除了一条提醒")
    SR.invoke('CommonEvent', 'RetryInput', item.guid)
}

const ManualInput = (item) => {

    proxy.$modal.alert("该包裹已转人工包装，请在操作界面查找当前包裹，解除料箱绑定！")
        .then(function () {
            SR.invoke('CommonEvent', 'ManualInput', item.guid)
        })

}

// 列配置
const tableColumns = [
    { prop: 'taskNo', label: '任务编号', width: '140px' },
    { prop: 'containerNo', label: '托盘号', width: '100px' },

    { prop: 'position', label: '位置', default: '未知位置', width: '160px' },
    { prop: 'taskStatusText', label: '状态', width: '160px' },
    { prop: 'createdTime', label: '接收时间', width: '160px' },
    { prop: 'operation', label: '操作', width: '400px' } // 插槽列
];

// 真实数据（实际项目中从接口获取）
const taskOrders = ref([]);

// 测试数据
const testStationsData = [
    //   {
    //     id: '1',
    //     name: '托盘进站-尺寸测量',
    //     location: '尺寸测量位',
    //     status: 2,
    //     taskId: 'T250822001',
    //     operateTime: '09:35:22'
    //   },
    //   {
    //     id: '2',
    //     name: '机械手抓取扫码校验',
    //     location: '机械手抓取位',
    //     status: 1,
    //     taskId: 'T250822001',
    //     operateTime: '09:36:10'
    //   },
];

// 状态文本映射
const getStatusText = (status) => {
    const statusMap = { 0: '-', 1: 'OK', 2: 'NG', 3: 'NG' };
    return statusMap[status] || '未知';
};

// 状态样式映射
const getStatusClass = (status) => {
    const classMap = {
        0: 'status-pending',
        1: 'status-completed',
        2: 'status-error'
    };
    return classMap[status] || 'status-pending';
};

// 行样式回调
const getRowClass = (row) => {
    return row.status === 1 ? 'row-running' : '';
};



// 父组件中的任务数据（实际项目中可能从接口获取）
const currentTaskNumber = ref('T20231030001'); // 示例任务编号
const currentOldBoxNumber = ref('AP789'); // 示例旧料箱号
// 重新绑定按钮事件
const handleRebind = (row) => {
    //打开弹框 
    currentTaskNumber.value = row.taskNo
    currentOldBoxNumber.value = row.containerNo
    proxy.$refs['rebindDialogRef'].show()
};

const handleDelete = async (row) => {
    const body = { taskNo: row.taskNo }
    try {
        await proxy.$modal.confirm('确定要删除吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'info', })
    } catch (error) {
        return
    }
    const res = await request({ url: `/api/packagingtask/deletetask`, method: 'post', data: body })
    proxy.$modal.loading('执行中')
    await new Promise(resolve => setTimeout(resolve, 700));
    proxy.$modal.closeLoading()
    proxy.$modal.alertSuccess('操作成功')
};
//handleUnbind
const handleUnbind = async (row) => {
    const body = { taskNo: row.taskNo }
    try {
        await proxy.$modal.confirm('确定要解除托盘绑定吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'info', })
    } catch (error) {
        return
    }
    const res = await request({ url: `/api/packagingtask/unbind`, method: 'post', data: body })
    proxy.$modal.loading('执行中')
    await new Promise(resolve => setTimeout(resolve, 700));
    proxy.$modal.closeLoading()
    proxy.$modal.alertSuccess('操作成功')
};
//handlePrint 
const handlePrint = async (row) => {

    proxy.$modal.alertSuccess('暂不支持')
};
const isMock = ref(true)
const childRef = ref(null)
const isMockBeforeChange = () => {
    // 如果是选中操作（开启模拟模式）
    const newstate = !childRef.value.innerIsMock
    let model = "2"
    if (newstate === true) {
        // 弹出确认提示
        model = "1"
    }
    return proxy.$modal.confirm(
        '确定要切换模式吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        }
    ).then(() => {
        SR.invoke('CommonEvent', 'ProductMode', model)
        return true;
    }).catch(() => {
        // SR.invoke('CommonEvent', 'ProductMode', '1')
        return false;
    })



}

// pnpm install @dataview/datav-vue3  pnpm install @jiaminghi/data-view
//npm uninstall @jiaminghi/data-view pnpm uninstall @dataview/datav-vue3
</script>
<style lang="scss" scoped>
@use './index.scss';
</style>
<style lang='scss' scoped>
.main-screen {
    position: absolute;
}

:deep(.card-container-root) {
    width: 100%;
    height: 100%;
}

.card-container {
    display: grid;
    /* 三行两列布局，为大卡片预留空间 */
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: auto auto auto;
    gap: 16px;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
}

/* 普通卡片 - 占据1x1网格 */
.normal-card {
    grid-column: span 1;
    grid-row: span 1;
}

/* 大卡片 - 占据1x2网格（跨两行） */
.large-card {
    grid-column: span 1;
    grid-row: span 2;
    /* 关键：让大卡片自然占据两行高度 */
}

/* 每个项目：占据1行1列的网格空间 */
.grid-item {
    grid-column: span 1;
    /* 占1列 */
    grid-row: span 1;
    /* 占1行（关键：强制每个项目只占1行高度） */
}







.table-container {
    width: 100%;
    overflow: hidden;
}

.el-table {
    border: none;
}

.el-table__body-wrapper {
    overflow: hidden;
    /* 隐藏滚动条 - Chrome、Safari 和 Opera */
    -ms-overflow-style: none;
    /* IE 和 Edge */
    scrollbar-width: none;
    /* Firefox */
}

.el-table__body-wrapper::-webkit-scrollbar {
    display: none;
    /* Chrome、Safari 和 Opera */
}

/* 取消表格行悬停变色效果
--el-table-row-hover-bg-color:
*/
.el-table {
    --el-table-row-hover-bg-color: inherit !important;
    --el-table-border-color: inherit !important;
}

:deep(.rowclass) {
    background-color: #030409;
    color: white;
}

.subtitle {
    font-size: 2vw;
}



:deep(.dv-scroll-board .rows) {
    border-radius: 10px;
    overflow: hidden;
}

:deep(div[tag="alarm"] > .dv-scroll-board .rows .row-item) {

    font-size: 1.5vw;
    color: #dbdad8;
}

// :deep(div[tag="alarm"] > .dv-scroll-board .rows .row-item>div:nth-child(1) ){
//     width: 100% !important;
// }

.background {
    background-color: #030409;
    color: white;
    height: 100%;
}

.page {
    flex: 1;
    display: flex;
    overflow: hidden;
    flex-direction: column;
}

.content {
    display: flex;
    justify-content: space-between;
    flex: 1;
    gap: 16px;
    box-sizing: border-box;
}

.flex-col {
    display: flex;
    flex: 1;
    height: 100%;
    flex-direction: column;

    .root {
        display: flex;
        flex-direction: column;
        flex: 1;
        height: 100%;
        gap: 16px;
    }
}

/* 设置 div 为圆形并添加红色渐变背景 */
.blinking-circle {
    //   width: 100px;
    //   height: 100px;
    border-radius: 50%;
    /* 红色渐变背景 */
    background: radial-gradient(circle at center, #ff0000, #800000);
    /* 应用闪烁动画 */
    animation: blink 1s infinite alternate;
}

/* 定义闪烁动画 */
@keyframes blink {
    0% {
        opacity: 1;
    }

    100% {
        opacity: 0.3;
    }
}



/* 滚动条轨道透明 */
/* 针对 flex-col 容器内的 el-scrollbar 垂直滚动条滑块 */
:deep(div.flex-col > .el-scrollbar > .el-scrollbar__bar.is-vertical > .el-scrollbar__thumb) {
    background-color: transparent !important;
}
</style>
